/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAFlyoutMenuViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/4/13.
//  Copyright (c) 2013 Redia A/S. All rights reserved.
//

#import "BAFlyoutMenuViewController.h"
#import "BAUtils.h"
#import <QuartzCore/QuartzCore.h>
#import "BARootViewController.h"
#import "MWFSlideNavigationViewController.h"
#import "BALibrarySettings.h"
#import "UIImage+MultiplyColor.h"
#import "BAPatronSettings.h"
#import "BABranch.h"
#import "LazyLoadManager.h"
#import "BALibrarySettings.h"
#import "InfoGalleriImageUrlUtils.h"
#import "BAFlyoutMenuTableViewCell.h"
#import "BAFlyoutMenuTableViewCellData.h"

#ifdef BA_LIBRARIAN_BUILD
#import "LBChooseFavoriteLibraryViewController.h"
#endif

#ifdef BA_IMF_BUILD
#import "IMFPackageEditManager.h"
#import "IMFGlobalPackageEditManager.h"
#endif

@interface BAFlyoutMenuViewController (){
    CAGradientLayer *backgroundGradient;
    NSArray* cells;
}

@end

@implementation BAFlyoutMenuViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    BA_LABEL_SET_FONT_THIN(self.versionNumberLabel);
    NSString *versionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
    if (versionString) {
        self.versionNumberLabel.text = [NSString stringWithFormat:@"Version: %@", versionString];
    }
    
    // Status bar background.
    if ([[BAUtils instance] iOSMajorVersion] < 7) {
        self.statusBarHeightConstraint.constant = 0;
    }
    
    // Background gradient.
    backgroundGradient = [CAGradientLayer layer];
    backgroundGradient.frame = self.view.bounds;
    UIColor *topColor = [UIColor colorWithWhite:32.0/255.0 alpha:1];
    UIColor *bottomColor = [UIColor colorWithWhite:87.0/255 alpha:1];
    [backgroundGradient setColors:@[ (id)topColor.CGColor, (id)bottomColor.CGColor ]];
    [self.view.layer insertSublayer:backgroundGradient atIndex:0];
    
    BA_LABEL_SET_FONT_LIGHT(self.branchLabel);
    
    BA_LABEL_SET_FONT_LIGHT(self.loggedInUserLabel);
    
    BA_BUTTON_ADD_LIGHT_PRESSED_STATE_OVERLAY(self.changeUserButton);
    BA_LABEL_SET_FONT_LIGHT(self.changeUserButton.titleLabel);
    [self.changeUserButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    self.changeUserButton.titleEdgeInsets = UIEdgeInsetsMake(0, 45, 0, 0);
    UIImage *changeUserImage = [UIImage imageNamed:@"padlock"];
    [self.changeUserButton setImage:changeUserImage forState:UIControlStateNormal];
    [self.changeUserButton setImage:[UIImage imageNamed:@"padlock" multiplyWithColor:[[BALibrarySettings instance] getCustomerColorNormal]] forState:UIControlStateHighlighted];
    [self.changeUserButton setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    
    if ([BARPCManager isStillAuthenticated]) {
        self.loggedInUserLabel.hidden = NO;
        self.changeUserButton.hidden = NO;
        self.loggedInUserLabel.text = [NSString stringWithFormat:@"Bruger: %@", [[BAPatronSettings instance] getLoggedInPatronName]];
    }
    
    if ([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
//        self.editorButton.hidden = NO;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(patronSettingsChanged:) name:BA_PATRON_SETTINGS_OBJECT_CHANGED object:nil];
    [self setupPatronBranchName];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(libraryChanged:) name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    [self setupLogo];
    

    if ([BARPCManager instance].isUsingDevServer) {
        CGRect devLabelRect = self.logoImageView.frame;
        devLabelRect.size = CGSizeMake(60, 16);
        UILabel* devLabel = [[UILabel alloc] initWithFrame:devLabelRect];
        devLabel.backgroundColor = [UIColor whiteColor];
        devLabel.textColor = [UIColor blackColor];
        devLabel.alpha = 0.4;
        devLabel.font = BA_FONT_LIGHT(9);
        devLabel.textAlignment = NSTextAlignmentCenter;
        devLabel.text = @"dev server";
        [self.view addSubview:devLabel];
    }
    
    NSMutableArray* cellButtons = [NSMutableArray new];
    
    if ([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
        BAFlyoutMenuTableViewCellData* chooseFavLibraryCellData = [BAFlyoutMenuTableViewCellData new];
        chooseFavLibraryCellData.title = @"Vælg favoritbibliotek";
        chooseFavLibraryCellData.image = [UIImage imageNamed:@"star-gray-small"];
        chooseFavLibraryCellData.identifier = @"choose-favorite-library";
        [cellButtons addObject:chooseFavLibraryCellData];

    }

    
    BAFlyoutMenuTableViewCellData* changeLibraryCellData = [BAFlyoutMenuTableViewCellData new];
    changeLibraryCellData.title = @"Skift kommune";
    changeLibraryCellData.image = [UIImage imageNamed:@"change-library"];
    changeLibraryCellData.identifier = @"change-library";
    [cellButtons addObject:changeLibraryCellData];
    
    if (!([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary] ||  [[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary])) {
        BAFlyoutMenuTableViewCellData* guideCellData = [BAFlyoutMenuTableViewCellData new];
        guideCellData.title = @"Guide";
        guideCellData.image = [UIImage imageNamed:@"related-icon-info"];
        guideCellData.identifier = @"guide";
        [cellButtons addObject:guideCellData];
    }
    
    if ([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary] || [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
    
        BAFlyoutMenuTableViewCellData* logoutAndEndCellData = [BAFlyoutMenuTableViewCellData new];
        logoutAndEndCellData.title = @"Log ud og afslut";
        logoutAndEndCellData.image = [UIImage imageNamed:@"house"];
        logoutAndEndCellData.identifier = @"logout";
        [cellButtons addObject:logoutAndEndCellData];
    }
    cells = [NSArray arrayWithArray:cellButtons];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupPatronBranchName) name:BA_PATRON_SETTINGS_LIBRARIAN_PREFERRED_BRANCH_CHANGED object:nil];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    backgroundGradient.frame = self.view.bounds;
}

- (void)libraryChanged:(id)sender
{
    [self setupLogo];
}

- (void)setupLogo
{
    NSString* logo_url = [[BALibrarySettings instance] getLogoUrlStringForType:BALibrarySettingsLogoUrlTypeDefault];
    if (logo_url!=nil && [logo_url length]>0) {
        NSString* resizeurl = [InfoGalleriImageUrlUtils getResizedImageUrl:logo_url
                                                                   toWidth:230
                                                                  toHeight:77
                                                              usingQuality:9
                                                                  withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX
                                                              outputFormat:@"png"
                                                         doubleUpForRetina:YES];
        
        [[LazyLoadManager instance] lazyLoadUIImageFromUrl:resizeurl
                                         setScaleforRetina:YES
                                                 onSuccess:^(UIImage *image) {
                                                     self.logoImageView.image = image;
                                                 }
                                                   onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
                                                       self.logoImageView.image = nil;
                                                   }
         ];
    } else {
        self.logoImageView.image=nil;
    }

}

- (void)patronSettingsChanged:(id)sender
{
    [self setupPatronBranchName];
}

- (void)setupPatronBranchName
{
    bool branchTextFound = false;
    NSString *branchCode = [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary] ? [[BAPatronSettings instance] getLibrarianPreferredMaterialHistoryBranchCode] : [[BAPatronSettings instance] getLoggedInPatronPreferredBranch];
    if (branchCode) {
        for (BABranch *branch in [[BALibrarySettings instance] branches]) {
            if ([branch.code isEqualToString:branchCode]) {
                self.branchLabel.text = branch.name;
                branchTextFound=true;
                break;
            }
        }
    }
    //make sure text in the label is not stale
    if (!branchTextFound) {
        self.branchLabel.text = @"";
    }
    
    self.loggedInUserLabel.text = [NSString stringWithFormat:@"Bruger: %@", [[BAPatronSettings instance] getLoggedInPatronName]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)showGuideButtonClicked:(id)sender {
    [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
    [[BARootViewController instance] showUserGuide];
}

- (IBAction)changeLibraryClicked:(id)sender
{
#ifdef BA_IMF_BUILD
    if ([IMFPackageEditManager instance].hasPackageChanged || [IMFGlobalPackageEditManager instance].hasPackageChanged) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Pakke er ændret" message:@"Der er ugemte ændringer i den pakke du er ved at editere. Tryk OK for at glemme ændringerne og forlade redaktør-tilstanden." delegate:self cancelButtonTitle:@"Annuller" otherButtonTitles:@"OK", nil];
        alert.tag = 0;
        [alert show];
    } else
#endif
    {
        [self changeLibrary];
    }
    
}


- (IBAction)goToFrontPageClicked:(id)sender
{
#ifdef BA_IMF_BUILD
    if ([IMFPackageEditManager instance].hasPackageChanged || [IMFGlobalPackageEditManager instance].hasPackageChanged) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Pakke er ændret" message:@"Der er ugemte ændringer i den pakke du er ved at editere. Tryk OK for at glemme ændringerne og forlade redaktør-tilstanden." delegate:self cancelButtonTitle:@"Annuller" otherButtonTitles:@"OK", nil];
        alert.tag = 1;
        [alert show];
    } else
#endif
    {
        [self removePatronCredentialsAndGoToAnonymousAppMode];
    }
}

- (IBAction)changeUserClicked:(id)sender
{
#ifdef BA_IMF_BUILD
    if ([IMFPackageEditManager instance].hasPackageChanged || [IMFGlobalPackageEditManager instance].hasPackageChanged) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Pakke er ændret" message:@"Der er ugemte ændringer i den pakke du er ved at editere. Tryk OK for at glemme ændringerne og forlade redaktør-tilstanden." delegate:self cancelButtonTitle:@"Annuller" otherButtonTitles:@"OK", nil];
        alert.tag = 2;
        [alert show];
    } else
#endif
    {
        [self changeUser];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        switch (alertView.tag) {
            case 0:
                [self changeLibrary];
                break;
            case 1:
                [self removePatronCredentialsAndGoToAnonymousAppMode];
                break;
            case 2:
                [self changeUser];
                break;
            default:
                break;
        }
        
    }
}

-(void)changeLibrary{
    [[BALibrarySettings instance] setLibraryObject:nil];
    [[BAPatronSettings instance] setHasPerformedSuccessfullLogin:NO];
    [[BAPatronSettings instance] setLoggedInUserName:@""];
    [[BAPatronSettings instance] setPatronObject:nil];
    [BARPCManager invalidateAuthenticatedSessionTimestamp];
    [[BARootViewController instance] switchToLibrarySelectionWithShowingLoginScreen:NO];
    [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
}

-(void)changeUser{
    [[BAPatronSettings instance] setHasPerformedSuccessfullLogin:NO];
    [[BAPatronSettings instance] setLoggedInUserName:@""];
    [[BAPatronSettings instance] setPatronObject:nil];
    [BARPCManager invalidateAuthenticatedSessionTimestamp];
    [[BARootViewController instance] switchToLibrarySelectionWithShowingLoginScreen:YES];
    [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
}

- (void)removePatronCredentialsAndGoToAnonymousAppMode
{
    [[BAPatronSettings instance] setHasPerformedSuccessfullLogin:NO];
    [[BAPatronSettings instance] setLoggedInUserName:@""];
    [[BAPatronSettings instance] setPatronObject:nil];
    [BARPCManager invalidateAuthenticatedSessionTimestamp];
    [self.slideNavigationViewController slideWithDirection:MWFSlideDirectionNone];
    [[BARootViewController instance] switchToUserLibraryAppMode];
}



-(void)librarianChooseFavoriteLibrary
{
#ifdef BA_LIBRARIAN_BUILD
    LBChooseFavoriteLibraryViewController* chooser = [LBChooseFavoriteLibraryViewController new];
    //TODO: animation
    [self.slideNavigationViewController addChildViewController:chooser];
    [self.slideNavigationViewController.view addSubview:chooser.view];
    chooser.view.frame = self.slideNavigationViewController.view.bounds;
    chooser.view.alpha=0;
    [UIView animateWithDuration:0.33
                     animations:^{
                         chooser.view.alpha=1;
                     }
     ];
#endif
}

#pragma UITableView Delegetes

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [cells count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BAFlyoutMenuTableViewCell* cell = [[[NSBundle mainBundle] loadNibNamed:@"BAFlyoutMenuTableViewCell" owner:self options:nil] objectAtIndex:0];
    BAFlyoutMenuTableViewCellData* data = [cells objectAtIndex:indexPath.row];
    cell.cellTitle.text = data.title;
    cell.cellImageView.image = data.image;
 
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor colorWithWhite:0.3f alpha:1.0f];
    bgColorView.layer.masksToBounds = YES;
    [cell setSelectedBackgroundView:bgColorView];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BAFlyoutMenuTableViewCellData* data = [cells objectAtIndex:indexPath.row];
    DLog(@"%@", data.identifier);

    if([data.identifier isEqualToString:@"change-library"]) {
        [self changeLibraryClicked:data];
    } else if([data.identifier isEqualToString:@"guide"]) {
        [self showGuideButtonClicked:data];
    } else if([data.identifier isEqualToString:@"logout"]) {
        [self goToFrontPageClicked:data];
    } else if([data.identifier isEqualToString:@"choose-favorite-library"]) {
        [self librarianChooseFavoriteLibrary];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_PATRON_SETTINGS_OBJECT_CHANGED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_PATRON_SETTINGS_LIBRARIAN_PREFERRED_BRANCH_CHANGED object:nil];
}

//This is a hack to get transparent cell background
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBackgroundColor:[UIColor clearColor]];
}

@end